<template>
	<view class="u-page">
		<!-- 选项 -->
		<view class="u-demo-block">
			<view>
				<u--form 
					labelPosition="left" 
					:labelWidth="80" 
					:model="formData" 
					:rules="formRules" 
					ref="form1">
					<!-- 设备号 -->
					<u-form-item 
						label="设备号" 
						required 
						prop="machineInfo.machineNo" 
						ref="machineNo">
						<u-input 
							v-model="formData.machineInfo.machineNo"
							clearable
							@blur="machineNoBlur">
						</u-input>
					</u-form-item>
					<view class="echo">
						<u--text 
							type="success" 
							:size="12"
							:text="echo.machineNo">
						</u--text>
					</view>
					<u-line :customStyle="{marginTop:'5px'}"></u-line>
					<!-- 查询方式 -->
					<u-form-item
						v-show="show.radio"
						label="查询方式" 
						required 
						prop="queryTypeValue" 
						ref="queryTypeValue">
						<u-radio-group
							v-model="formData.queryTypeValue"
							placement="column"
							@change="radioGroupChange">
							<u-radio
								v-for="(item,index) in radioList"
								:key="index"
								:label="item.name"
								:name="item.name">
								
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<!-- 选择日期 -->
					<u-form-item
						v-show="show.beginDatePickerItem"
						label="开始日期"
						prop="beginDatePickerValue"
						ref="beginDatePicker"
						@click="beginDatePickerClick">
						<u-input
							v-model="formData.beginDatePickerValue"
							disabled
							disabledColor="#ffffff"
							placeholder="请选择作业项目"
							fontSize="13px"
							color="#12569F"
							suffixIcon="arrow-right">
							
						</u-input>
						
					</u-form-item>
					<u-form-item
						v-show="show.endDatePickerItem"
						label="结束日期"
						prop="endDatePickerValue"
						ref="endDatePicker"
						@click="endDatePickerClick">
						<u-input
							v-model="formData.endDatePickerValue"
							disabled
							disabledColor="#ffffff"
							placeholder="请选择作业项目"
							fontSize="13px"
							color="#12569F"
							suffixIcon="arrow-right">
							
						</u-input>
						
					</u-form-item>
					
				</u--form>
			</view>
		</view>
		<!-- button组 -->
		<view class="u-demo-block">
			<u-row
				:customStyle="{marginTop:'8px'}"
				justify="between"
				gutter="20">
				<u-col span="6">
					<view style="padding: 0 10px">
						<u-button 
							type="primary"
							text="查询"
							@click="formSubmit()">
						</u-button>
					</view>
				</u-col>
				<u-col span="6">
					<view style="padding: 0 10px;">
						<u-button
							plain
							type="warning"
							text="重置"
							@click="formReset()">
							</u-button>
					</view>
				</u-col>

			</u-row>
		</view>
		
		<view class="u-demo-block">
			<YSteps 
				:lineNum="0" 
				color="#fff" 
				backgroundColor="#000fff" 
				:infoList="recordTimeLine.resultList"
				@click="ystepclick"
				@longprs="ysteplongpress">
			</YSteps>
			
			<u-loadmore 
				:status="recordTimeLine.loadStatus" 
				:icon="true"
				@loadmore="loadmore">
			</u-loadmore>
		</view>
		
		<u-datetime-picker
			:show="show.beginDatePicker"
			v-model="tempBeginDateValue"
			:maxDate="new Date().getTime()"
			mode="date"
			closeOnClickOverlay
			@close="show.beginDatePicker=false"
			@cancel="show.beginDatePicker=false"
			@confirm="beginDatePickerConfirm">
			
		</u-datetime-picker>

		<u-datetime-picker
			:show="show.endDatePicker"
			v-model="tempEndDateValue"
			:maxDate="new Date().getTime()"
			mode="date"
			closeOnClickOverlay
			@close="show.endDatePicker=false"
			@cancel="show.endDatePicker=false"
			@confirm="endDatePickerConfirm">
			
		</u-datetime-picker>
		<u-back-top
			:scroll-top="scrollTop">
		</u-back-top>
		<u-popup
			:show="popupData.popupShow"
			closeable
			closeOnClickOverlay
			mode="left"
			@close="popupData.popupShow=false">
			<view class="u-demo-block u-flex-center poputview">
				<scroll-view
					class="scroll-Y"
					:style="scrollStyle"
					:scroll-top="popupData.scrollTop" 
					scroll-y="true">
					<u-cell-group>
						<!-- <u-cell v-show="(popupData.cellData.userFullName)!=''&& popupData.cellData.userFullName!=null" title="型名" :label="popupData.cellData.userFullName"></u-cell> -->
						<u-cell v-show="!$u.test.isEmpty(popupData.cellData.recordTime)" title="日期" :label="popupData.cellData.recordTime"></u-cell>
						<u-cell v-show="!$u.test.isEmpty(popupData.cellData.userFullName)" title="姓名" :label="popupData.cellData.userFullName"></u-cell>
						<u-cell v-show="!$u.test.isEmpty(popupData.cellData.machineNo)" title="设备号" :label="popupData.cellData.machineNo"></u-cell>
						<u-cell v-show="!$u.test.isEmpty(popupData.cellData.planOutput)" title="计划生产数" :label="popupData.cellData.planOutput"></u-cell>
						<u-cell v-show="!$u.test.isEmpty(popupData.cellData.actualOutput)" title="实际生产数" :label="popupData.cellData.actualOutput"></u-cell>
						<u-cell v-show="!$u.test.isEmpty(popupData.cellData.defect)" title="不良数" :label="popupData.cellData.defect"></u-cell>
						<u-cell v-show="!$u.test.isEmpty(popupData.cellData.recordRemark)" title="备注" :label="popupData.cellData.recordRemark"></u-cell>
						

					</u-cell-group>
				</scroll-view>
			</view>
		</u-popup>
		<u-modal 
			:show="modalData.show"
			:showCancelButton="true"
			title="密码确认"
			:asyncClose="true"
			@confirm="modalConfirm"
			@cancel="modalData.show=false">
			<view>
				<u-text type="primary" :text="modalData.text"></u-text>
				<u-input
					v-model="modalData.input"
					customStyle="marginTop:8px"
					type="password"
					placeholder="请输入密码">
				</u-input>
			</view>
		</u-modal>
	</view>
</template>

<script>
import {getMachineNoEcho2} from '@/api/machine/machine.js'
// import {getRecordTimeLine} from "@/api/recordtimeline/recordtimeline.js"
import {getShiftCapaRecordTimeLine} from '@/api/shiftcaparecord/shiftcaparecord.js'
import {checkUserPassword} from '@/api/user/user.js'

// 引用时间计算库
import timer from '@/js_sdk/xbc-timer/timer-1.1.6.js';
import YSteps from '@/components/Y-Steps/Y-Steps2.vue';

//引用dayjs
import dayjs from '@/uni_modules/uview-ui/libs/util/dayjs.js'

export default {
	components: {
		YSteps
	},
	data() {
		return {
			formData: {
				machineInfo:{
					machineNo:''
				},
				// machineNo: '',
				queryTypeValue:'一般查询',
				calendarValue:'',
				beginDatePickerValue: timer.getToday(),
				endDatePickerValue: timer.getTomorrow(),
			},
			formRules: {
				'machineInfo.machineNo': [
					{
						type: 'string',
						required: true,
						message: '不能为空',
						trigger: ['change','blur'],
					},
					//异步验证
					{
						asyncValidator:(rule,value,callback)=>{
							if(uni.$u.test.isEmpty(value)){
								return
							}
							getMachineNoEcho2({machineNo:this.formData.machineInfo.machineNo})
								.then(res=>{
									// this.echo.machineNo=res.data.topDept.topDeptName+'\n' + res.data.secDept.secDeptName + '\n' + res.data.machine.machineName
									this.echo.machineNo=res.data.machineName
									this.show.radio=true
									callback()
								})
								.catch(err=>{
									console.log(err);
									callback(new Error(err.message|| err.msg || (err.errMsg+'; 服务器异常')))
								})
						}
					}
				],
				queryTypeValue:[
					{
						type: 'string',
						required: true,
						message: '不能为空',
						trigger: ['change'],
					}
				],
				beginDatePickerValue:[
					{
						type: 'string',
						required: true,
						message: '不能为空',
						trigger: ['change','blur'],
					},
					{
						validator: (rule, value, callback) => {
							if(!uni.$u.test.date(value)){
								return false
							}
							if(!uni.$u.test.date(this.formData.endDatePickerValue)){
								return false
							}
							if(new Date(value).getTime() > new Date(this.formData.endDatePickerValue).getTime()){
								return false
							}
							return true
						},
						message:'开始大于结束'
					}
				],
				endDatePickerValue:[
					{
						type: 'string',
						required: true,
						message: '不能为空',
						trigger: ['change','blur'],
					},
					{
						validator: (rule, value, callback) => {
							
							if(!uni.$u.test.date(this.formData.beginDatePickerValue)){
								return false
							}
							if(!uni.$u.test.date(value)){
								return false
							}
							if(new Date(value).getTime() < new Date(this.formData.beginDatePickerValue).getTime()){
								return false
							}
							return true
						},
						message:'开始大于结束'
					}
				],
				
			},
			// 回显
			echo:{
				machineNo:''
			},
			// show
			show:{
				radio:false,
				beginDatePickerItem:false,
				endDatePickerItem:false,
				beginDatePicker:false,
				endDatePicker:false
			},
			radioList:[
				{
					name:'一般查询'
				},
				{
					name:'时间段查询'
				}
			],
			//定时器
			timer:{
				machineNo:0,
				pulldown:0
			},
			// tempBeginDateValue:uni.$u.timeFormat(Number(new Date()),'yyyy-mm-dd'),
			tempBeginDateValue:Number(new Date(timer.getToday())),
			tempEndDateValue:Number(new Date(timer.getTomorrow())),
			
			// loadmore测试数据
			status: 'loadmore',
			list: 1,
			page: 0,
			// 回到顶部
			scrollTop:0,
			// 时间轴用数据
			recordTimeLine:{
				beginTime:timer.getToday(),
				endTime:timer.getTomorrow(),
				dateInterval:2,
				resultList:[],
				resultListPojo:[],
				loadStatus:'nomore'
			},
			popupData:{
				popupShow: false,
				scrollTop: 0,
				cellData:{
					recordTime:'',
					userFullName:'',
					machineNo:'',
					planOutput:'',
					actualOutput:'',
					defect:'',
					recordRemark:'',		
				}
			},
			modalData:{
				longprzData:null,
				show:false,
				text:'',
				input:''
			},
		};
	},
	onUnload() {
		clearTimeout(this.timer.machineNo)
	},
	onPullDownRefresh() {
		// 页面下拉刷新的生命周期
		const _this = this;
		this.formSubmit()
		this.timer.pulldown=setTimeout(() => {
			_this.formSubmit()
			uni.stopPullDownRefresh();
		}, 1500);
		// this.async_await_test()
	},
	onNavigationBarButtonTap(e) {
		if (e.type === 'menu') {
			// this.showMenuDrawer();
		} else if (e.type === 'home') {
			uni.reLaunch({
				url: '/pages/index/index'
			});
		}
	},
	onPageScroll(e) {
		this.scrollTop=e.scrollTop
	},
	onReachBottom() {
		if(this.recordTimeLine.loadStatus!='nomore'){
			this.funcGetRecordTimeLine()
		}
	},

	computed:{
		scrollStyle(){
			return {
				'height':uni.$u.sys().windowHeight+'px'
			}
		}
	},
	methods: {

		machineNoBlur() {
			this.timer.machineNo=setTimeout(()=>{
				this.$refs.form1.validateField('machineInfo.machineNo');
			},666)
		},
		radioGroupChange(e){
			// 显示选择事件
			if(e=='时间段查询'){
				this.show.beginDatePickerItem=true
				this.show.endDatePickerItem=true

			} else {
				this.show.beginDatePickerItem=false
				this.show.endDatePickerItem=false
			}
		},
		beginDatePickerClick(){
			this.show.beginDatePicker=true
			// #ifdef APP-PLUS
			uni.hideKeyboard()
			// #endif
		},
		endDatePickerClick(){
			this.show.endDatePicker=true
			// #ifdef APP-PLUS
			uni.hideKeyboard()
			// #endif
		},
		beginDatePickerConfirm(e){
			this.show.beginDatePicker=false
			this.formData.beginDatePickerValue=uni.$u.timeFormat(e.value,'yyyy-mm-dd')
			this.$refs.form1.validateField('beginDatePickerValue')
		},
		endDatePickerConfirm(e){
			this.show.endDatePicker=false
			this.formData.endDatePickerValue=uni.$u.timeFormat(e.value,'yyyy-mm-dd')
			this.$refs.form1.validateField('endDatePickerValue')
		},
		formSubmit(){
			this.$refs.form1.validate()
				.then(res=>{
						this.recordTimeLine.resultList=[]
						this.recordTimeLine.resultListPojo=[]

					if(this.formData.queryTypeValue=='一般查询'){
						this.recordTimeLine.beginTime= timer.getToday()
						this.recordTimeLine.endTime= timer.getTomorrow()
						this.recordTimeLine.dateInterval=2
						this.funcGetRecordTimeLine();
					}
					else {
						this.recordTimeLine.loadStatus='nomore'
						this.recordTimeLine.beginTime=this.formData.beginDatePickerValue
						this.recordTimeLine.endTime=this.formData.endDatePickerValue
						this.funcGetRecordTimeLine('nomore');
						
					}
				})
				.catch(err=>{
					console.log(err);
				})
		},
		formReset(){
			this.$refs.form1.resetFields()
			this.initData()
		},
		// 初始化数据
		initData(){
			this.formData.machineInfo.machineNo=''
			this.queryTypeValue='一般查询'
			this.calendarValue=''
			this.beginDatePickerValue=timer.getToday()
			this.endDatePickerValue= timer.getTomorrow()
			this.echo.machineNo=''
			this.show.radio=false
			this.show.beginDatePickerItem=false
			this.show.endDatePickerItem=false
			this.show.beginDatePicker=false
			this.show.endDatePicker=false
			this.timer.machineNo=0
			this.timer.pulldown=0
			this.tempBeginDateValue=Number(new Date(timer.getToday()))
			this.tempEndDateValue= Number(new Date(timer.getTomorrow()))
			this.status='loadmore'
			this.list=1
			this.page= 0
			this.scrollTop=0
			this.recordTimeLine.beginTime=timer.getToday()
			this.recordTimeLine.endTime=timer.getTomorrow()
			this.recordTimeLine.dateInterval=2
			this.recordTimeLine.resultList=[]
			this.recordTimeLine.resultListPojo=[]
			this.recordTimeLine.loadStatus='nomore'
			this.modalData.longprzData=null;
			this.modalData.show=false
			this.modalData.text=''
			this.modalData.input=''
		},
		loadmore(){
			this.funcGetRecordTimeLine()
			// this.status = 'loading';
			// this.page = ++ this.page;
			// setTimeout(() => {
			// 	this.list += 10;
			// 	this.calcRecordTimeLineDate()
			// 	if(this.page >= 3) this.status = 'nomore';
			// 	else this.status = 'loading';
			// }, 2000)
		},
		calcRecordTimeLineDate(){
			this.recordTimeLine.beginTime= timer.getLatestDates(this.recordTimeLine.dateInterval)[0]
			this.recordTimeLine.endTime = timer.getLatestDates(this.recordTimeLine.dateInterval-1)[0]
			this.recordTimeLine.dateInterval+=1
			
		},
		// 获取时间线函数
		funcGetRecordTimeLine(status){
			this.recordTimeLine.loadStatus='loading'			
			
			// let begintime = (/^[0-9]+.?[0-9]*$/.test(this.recordTimeLine.beginTime))?this.recordTimeLine.beginTime:new Date(this.recordTimeLine.beginTime).getTime()
			// let endtime = (/^[0-9]+.?[0-9]*$/.test(this.recordTimeLine.endTime))?this.recordTimeLine.endTime:new Date(this.recordTimeLine.endTime).getTime()
			
			let begintime = this.recordTimeLine.beginTime+ " 07:00:00"
			let endtime = this.recordTimeLine.endTime+" 07:00:00"
			
			getShiftCapaRecordTimeLine(
				{
					machineNo:this.formData.machineInfo.machineNo,
					beginDate:begintime,
					endDate: endtime
				}
			)
				.then(res=>{
					// let utcTimeOffset2 = new Date().getTimezoneOffset()
					if(uni.$u.test.array(res.data)){
						res.data.forEach(item=>{
							// if(utcTimeOffset2!=(-480) && !uni.$u.test.isEmpty(item.recordTime)){
							// 	item.recordTime=item.recordTime-(utcTimeOffset2-480)*60000
							// }
							
							/*
							// 换算成1值
							if(new Date(item.recordTimeDT).getHours().toString()=='20'){
								item.recordTimeDT=uni.$u.timeFormat(item.recordTimeDT,'yyyy年mm月dd日')+' 1值' 
							} 
							//换算成2值
							else if (new Date(item.recordTimeDT).getHours().toString()=='8'){ 
								item.recordTimeDT=uni.$u.timeFormat(dayjs(item.recordTimeDT).add(-1,'day'),'yyyy年mm月dd日')+' 2值'
							} 
							else{
								item.recordTimeDT=uni.$u.timeFormat(item.recordTimeDT,'yyyy年mm月dd日 hh点')
							}
							*/
							item.recordTimeDT=uni.$u.timeFormat(item.recordTimeDT,'yyyy年mm月dd日 hh点')
							this.recordTimeLine.resultList.push(
								{
									date:item.recordTimeDT,
									info:'计划生产数: '+item.planOutput+' kpcs\n实际生产数: ' +item.actualOutput + ' kpcs\n不良数'+'\u3000\u3000' +': ' + item.defect +' pcs'
									
								}
							)
							this.recordTimeLine.resultListPojo.push(item)
						})
					}else {
						uni.$u.toast('服务器数据异常')
					}
				})
				.catch(err=>{
					uni.$u.toast(err.msg)
				})
				.finally(()=>{
					this.calcRecordTimeLineDate()
					if(status=='nomore'){
						this.recordTimeLine.loadStatus='nomore'
					}else {
						this.recordTimeLine.loadStatus='loadmore'
					}
				})
		},
		// 时间轴点击事件
		ystepclick(e){
			console.log(this.recordTimeLine.resultListPojo[e]);
			
			this.popupData.cellData.recordTime=this.recordTimeLine.resultListPojo[e].recordTimeDT
			this.popupData.cellData.userFullName=this.recordTimeLine.resultListPojo[e].userFullName
			this.popupData.cellData.machineNo=this.recordTimeLine.resultListPojo[e].machineNo
			this.popupData.cellData.planOutput=this.recordTimeLine.resultListPojo[e].planOutput
			this.popupData.cellData.actualOutput=this.recordTimeLine.resultListPojo[e].actualOutput
			this.popupData.cellData.defect=this.recordTimeLine.resultListPojo[e].defect
			this.popupData.cellData.recordRemark= this.recordTimeLine.resultListPojo[e].recordRemark

			this.popupData.popupShow=true
		},
		ysteplongpress(e){
			console.log(this.recordTimeLine.resultListPojo[e]);
			if(uni.$u.test.isEmpty(this.recordTimeLine.resultListPojo[e].recordTimeDT)){
				uni.$u.toast('数据异常')
				return
			} else if(this.recordTimeLine.resultListPojo[e].recordTimeDT.includes('合计')){
				uni.$u.toast('合计无法修改')
				return
			}
			
			if(uni.$u.test.isEmpty(this.recordTimeLine.resultListPojo[e].shiftCapaRecordID)){
				uni.$u.toast('ID数据异常')
				return
			}
			this.modalData.longprzData=this.recordTimeLine.resultListPojo[e]
			//输入作业者的密码
			this.modalData.text="账户: "+ this.recordTimeLine.resultListPojo[e].userCode+ "的密码"
			this.modalData.input=''
			this.modalData.show=true
		},
		// 模态框确认事件
		modalConfirm(){
			checkUserPassword({
				userCode:this.modalData.longprzData.userCode,
				userPassword:this.modalData.input
			}).then((res)=>{
				uni.navigateTo({
					url:'/pages/shift-capacity-record-input/shift-capacity-record-edit?shiftCapaRecordID=' +this.modalData.longprzData.shiftCapaRecordID
				})
			}).catch((err)=>{
				uni.$u.toast('密码错误')
			}).finally(()=>{
				this.modalData.show=false
			})
			
		}
	},

};
</script>

<style lang="scss" scoped>
.echo {
	margin-left: 80px;
	font-size: 16px;
}
.u-radio{
	margin-bottom: 8px;
	&:last-child{
		margin-bottom: 0px;
	}
}
.poputview{
	width: 375rpx; 
	background-color: palegoldenrod;
	word-wrap: break-word;
	word-break: break-all;
	
}

// scoped穿透
.poputview ::v-deep .u-cell__label{
	font-size:14px
}
// .item {
// 	line-height: 80rpx;
// 	padding: 24rpx 0;
// 	color: $u-content-color;
// 	font-size: 28rpx;
// }
</style>
